package org.markwebb.mina.playground.udp.client;

import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
import org.apache.mina.common.IoFuture;
import org.apache.mina.common.IoFutureListener;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.transport.socket.nio.DatagramConnector;
import org.markwebb.mina.playground.udp.server.UDPServer;

public class UDPClient extends IoHandlerAdapter {

	private File datafile;
	private IoSession session;
	private IoConnector connector;
	
	public UDPClient() throws IOException{

		Console console = System.console();
		//String file = console.readLine("%s", "Please enter a wav file to transmit : ");
		String file = "c:/wget.exe";
		datafile = new File( file );
		if( datafile.exists() && datafile.canRead() ){
			connector = new DatagramConnector();
			connector.setHandler( this );
			javaClient( datafile );
		} else {
			System.out.println("Cannot load file...");
		}
		
	}
	
	private void javaClient( File datafile ) throws IOException{
		ConnectFuture connFuture = connector.connect( new InetSocketAddress(UDPServer.PORT));
		connFuture.addListener( new IoFutureListener(){
			public void operationComplete(IoFuture future) {
				ConnectFuture connFuture = (ConnectFuture)future;
				if( connFuture.isConnected() ){
					System.out.println("...connected");
					session = future.getSession();
					sendData();
				}
			}
		});
	}
	
	private void sendData(){
		
		System.out.println("Sending data...");
		
		FileInputStream fin = null;
		try{
			fin = new FileInputStream( datafile );
			int read = 0;
			byte[] buffer = new byte[512];
			while( (read = fin.read(buffer)) != -1 ){
				ByteBuffer bb = ByteBuffer.allocate( read );
				bb.put(buffer, 0, read);
				session.write( bb );
				System.out.print("#");
			}
			
			System.out.println();
			
			fin.close();
		}catch(IOException ioe){
		}finally{
			if( fin != null ) {
				try {
					fin.close();
				}catch(IOException e){ }
			}
		}
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		new UDPClient();
	}
}
